from rclass import *

def rc(data,minObs=4) :  return r(data,RC(data,minObs))

def r(data,control):
  breaks=[] 
  def recurse(lst,all,pos=1) :
    "recurse on good splits of 'lst', if they exists"
    cut,below,above = split(lst,all)
    if not cut:
      for x in lst: x.rank = pos
    else:
      breaks += below.max
      pos = recurse(lst[:cut],below,pos) + 1
      pos = recurse(lst[cut:],above,pos)
    return pos
  def split(lst,all):
    "find  best cut of 'lst' into 'lhs' and 'rhs'"
    before, lhs = control.now0(), lst[0]
    cut, now, above, below= None, None, None, None
    for i,one in enumerate(lst):
      if i==0: continue
      rhs = all - lhs
      if rhs.n >= control.minObs:
        if lhs.n >= control.minObs:
          now = control.now(all,lhs,rhs)
          if control.better(before,now):
            if control.different(lhs,rhs) :
              before,cut  = now,i
              below,above = lhs.copy(),rhs.copy()
      lhs += one
    return cut,below,above
  bags = sorted(data)
  recurse(bags,reduce(lambda x,y:x+y,bags))
  return breaks,bags
